package org.lvhengchang.schoolmanager.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.lvhengchang.schoolmanager.bean.Admin;
import org.lvhengchang.schoolmanager.service.AdminService;
import org.lvhengchang.schoolmanager.service.impl.AdminServiceImpl;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private AdminService adminService = new AdminServiceImpl();

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username").trim();
		String password = request.getParameter("password").trim();
		HttpSession session = request.getSession();
		try {
			Admin result = adminService.login(username, password);
			if (result != null) {
				session.setAttribute("login", result);
				response.sendRedirect(request.getContextPath() + "/main/main.jsp");
			} else {
				request.setAttribute("errorMessage", "您输入的用户名或密码错误，请重试！");
				request.getRequestDispatcher("/login/login.jsp").forward(request, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
